package com.jic.point.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.common.Result;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.ConfActivityRuleApplyMapper;
import com.jic.point.mapper.ConfActivityRuleMapper;
import com.jic.point.mapper.ConfPlatformMapper;
import com.jic.point.model.entity.ConfActivityRule;
import com.jic.point.model.entity.ConfActivityRuleApply;
import com.jic.point.service.ConfActivityRuleApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ConfActivityRuleApplyServiceImpl implements ConfActivityRuleApplyService {

	@Resource
	private ConfActivityRuleApplyMapper mapper;
	@Resource
	private ConfActivityRuleMapper ruleMapper;
	@Resource
	private ConfPlatformMapper confPlatformMapper;

    @Override
    public int insertSelective(ConfActivityRuleApply request) {
        int flag = mapper.insertSelective(request);
        if(flag == 1 ){
            return  1;
        }else{
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }

    /**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(ConfActivityRuleApply request) {
	 int flag = mapper.insert(request);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public int saveOrUpdate(ConfActivityRuleApply request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				// 审核表修改
				//不用修改主表信息
				//判断积分是否做了改变
				ConfActivityRuleApply confActivityRuleApplyUpdate = mapper.selectByPrimaryKey(request);
				//比较修改后的 总积分 和 修改前的总积分是否一样
				if(confActivityRuleApplyUpdate.getTotal().compareTo(request.getTotal())!=0){
					//查询相差 负数代表 积分下调 正数代表积分上调
					BigDecimal subtract = request.getTotal().subtract(confActivityRuleApplyUpdate.getTotal());
					//修改绑定平台的积分
					ConfActivityRule confActivity = new ConfActivityRule();
					BeanUtils.copyProperties(request,confActivity);
					confActivity.setAvailable(subtract);
					confActivity.setDescription("修改活动总积分");
					// 修改平台积分
					int i = confPlatformMapper.activityRuleDeductionPoints(confActivity);
					if (i < 1)  throw new AppRuntimeException(ResponseCode.ELSE_REEOE,"请保证积分是否充足！");
					if(subtract.signum()==1){ confActivity.setType(1); }else { confActivity.setType(2); }
					//积分冻结成功，插入积分流水表中
					int i1 = ruleMapper.insertActiveRuleLog(confActivity);
					if(subtract.signum()==1){ confActivity.setType(3); }else { confActivity.setType(4); }
					//积分冻结插入平台流水表中delete
					int i2 = confPlatformMapper.insertPlatFromLog(confActivity);
					//判断  如果积分修改了  更改活动总积分 和 可用积分
					request.setAvailable(confActivityRuleApplyUpdate.getAvailable().add(subtract));
					request.setLimited(confActivityRuleApplyUpdate.getAvailable().add(subtract));
				}
				int flag = mapper.updateByPrimaryKey(request);
				if(flag == 1){
				  return 1;
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.insertSelective(request);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

	/**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(ConfActivityRuleApply request) {
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(ConfActivityRuleApply request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(ConfActivityRuleApply request){
		try {
			log.info("修改记录");
			ConfActivityRuleApply param = new ConfActivityRuleApply();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 根据code逻辑删除 对外提供调用
	 * @param confActivityRule
	 * @return
	 */
	@Override
	public  Result<Integer> updateByCode(ConfActivityRuleApply confActivityRule) {
		log.info("入参{}", JSON.toJSONString(confActivityRule));
		if(confActivityRule.getCode()==null){
			return Result.error("2001","权益编码不能为空");
		}
		confActivityRule.setDeleteFlag(1);
		Integer i = mapper.updateByCode(confActivityRule);
		if(i==null){
			return Result.error("2002","删除失败");
		}
		return Result.success("0000",i);
	}
	/**
	 * 根据code进行审核 对外提供调用
	 * @param confActivityRule
	 * @return
	 */
	@Override
	@Transactional
	public Result<Integer> updateByCodeAudit(ConfActivityRuleApply confActivityRule) {
		log.info("入参{}", JSON.toJSONString(confActivityRule));
		if(null==confActivityRule.getCode() || "".equals(confActivityRule.getCode())){
			return Result.error("2001","活动编码不能为空");
		}
		if(null==confActivityRule.getAuditSts() || "".equals(confActivityRule.getCode())){
			return Result.error("2008","审核类型不能为空");
		}
		if(null==confActivityRule.getAuditReason() || "".equals(confActivityRule.getCode())){
			return Result.error("2003","审核原因不能为空");
		}
		if(null==confActivityRule){
			return Result.error("2007","参数为空");
		}
		ConfActivityRuleApply conf=new ConfActivityRuleApply();
		conf.setCode(confActivityRule.getCode());
		//根据code查找是否有对应的活动
		ConfActivityRuleApply confActivityRuleApply = mapper.selectByCode(conf);
		if(null==confActivityRuleApply && "".equals(confActivityRule.getCode())){
			return Result.error("2006","活动编码不是有效的");
		}
		//有对应的活动则copy一份到主表
		ConfActivityRule rule=new ConfActivityRule();
		BeanUtils.copyProperties(confActivityRuleApply,rule);
		int i1 = ruleMapper.insertSelective(rule);
		//将申请表中的数据进行逻辑删除
		confActivityRule.setDeleteFlag(1);
		Integer i = mapper.updateByCode(confActivityRule);
		if(null==i){
		return 	Result.error("2004","审核失败");
		}


		return Result.success("0000",i);
	}
	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public ConfActivityRuleApply getByPrimaryKey(ConfActivityRuleApply request) {
		return mapper.selectByPrimaryKey(request);
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageInfo<ConfActivityRuleApply> listPageBySelective(ConfActivityRuleApply request, int pageNum, int pageSize) {
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" create_time desc");
	List<ConfActivityRuleApply> list = mapper.listPageBySelective(request);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<ConfActivityRuleApply> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return new PageInfo(list);
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<ConfActivityRuleApply> listAllRecord(ConfActivityRuleApply request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public BigDecimal queryAvailablePoint(String busiCode) {
		BigDecimal available= ruleMapper.queryAvailablePoint(busiCode);
		return available;
	}


}
